﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using LojaVirtual.Comuns.Clientes;
using LojaVirtual.Infra;
using LojaWeb.Models;

namespace LojaWeb.Controllers
{
	public class ClienteController : Controller
	{
		private UnitOfWork db;

		public ClienteController()
		{
			db = new UnitOfWork();
		}

		public ViewResult Index(int id)
		{
			var cliente = db.Clientes.Recuperar(id);
			return View(cliente);
		}

		public ViewResult Login()
		{
			return View();
		}

		[HttpPost]
		public ActionResult Login(Cliente cliente, string returnUrl)
		{
			try
			{
				this.Logar(cliente, db);
				if (Url.IsLocalUrl(returnUrl) && returnUrl.Length > 1 && returnUrl.StartsWith("/")
						&& !returnUrl.StartsWith("//") && !returnUrl.StartsWith("/\\"))
				{
					return Redirect(returnUrl);
				}
				else
				{
					return RedirectToAction("Index", "Home");
				}
			}
			catch (Exception)
			{
				ModelState.AddModelError("Email", "Falha no login");
				ModelState.AddModelError("Senha", "Falha no login");
				return View();
			}

		}

		public ActionResult Logout()
		{
			Session.Abandon();
			return RedirectToAction("Index", "ProdutoLoja");
		}

		public ActionResult Create()
		{
			return View();
		}

		[HttpPost]
		public ActionResult Create(Cliente cliente)
		{
			if (ModelState.IsValid)
			{
				db.Clientes.Inserir(cliente);
				db.SalvarAlteracoes();
				return RedirectToAction("Index", "Home");
			}

			return View(cliente);
		}

		public ActionResult Edit(int id)
		{
			Cliente cliente = db.Clientes.Recuperar(id);
			return View(cliente);
		}

		[HttpPost]
		public ActionResult Edit(Cliente cliente)
		{
			if (ModelState.IsValid)
			{
				db.Clientes.Atualizar(cliente);
				db.SalvarAlteracoes();
				return RedirectToAction("Index");
			}
			return View(cliente);
		}

		protected override void Dispose(bool disposing)
		{
			db.Dispose();
			base.Dispose(disposing);
		}
	}
}